<template>
  <BasicDrawer
    :destroyOnClose="true"
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    title="核销"
    width="520px"
    @ok="onSave(2)"
    okText="核销并开单"
    :maskClosable="false"
  >
    <template #centerFooter>
      <a-button danger @click="onSave(1)"> 仅核销</a-button>
    </template>
    <div class="card">
      <BasicForm @register="registerForm1" class="form">
        <template #memberSource="{ model, field }">
          <div class="data-group">
            <div
              :class="['use', 'cell', model[field] === o.value ? 'active tri-active-2' : 'tacit']"
              v-for="o in verifyTypes"
              :key="o.value"
              @click="model[field] = o.value"
            ><img :src="o.icon" alt="" style="width: 36px; object-fit: contain;"/>

              <div class="tri-symbol-2"></div>
              <div v-if="model[field] === o.value" class="tri-checked-2">
                <CheckOutlined />
              </div>
            </div>
          </div>
        </template>
        <template #mobile="{ model, field }">
          <div>
            <a-input placeholder="请输入客户手机号" v-model:value="model[field]" @change="onChengeIPhone"></a-input>
          </div>
          <div style="margin-top: 4px; font-weight: 400; font-size: 14px; color: #666666">
            输入用户信息后，将默认为其注册为客户
          </div>
        </template>
      </BasicForm>
    </div>
  </BasicDrawer>
</template>
<script setup>
  import { reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { useMessage } from '@/hooks/web/useMessage';
  import { verifyTypes } from '@/api/ds.js';
  import { CheckOutlined } from '@ant-design/icons-vue';
  import { POST,PAGE } from '@/api/http.js';

  const router = useRouter();

  const emit = defineEmits(['complete']);

  const state = reactive({
    required: false,
    memberCode:'-1'
  });
  const { createMessage, createConfirm } = useMessage();

  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '购买平台',
        field: 'memberSource',
        required: true,
        component: 'RadioGroup',
        slot: 'memberSource',
      },

      {
        label: '核销码',
        field: 'verificationCode',
        component: 'Input',
        required: true,
      },
      {
        label: '客户姓名',
        field: 'memberName',
        component: 'Input',
        required: false,
        componentProps: {
          placeholder: '请输入客户姓名'
        },
      },

      {
        label: '手机号',
        field: 'memberMobile',
        component: 'Input',
        required: false,
        slot: 'mobile',
        componentProps: {
          placeholder: '请输入客户手机号'
        },
        rules: [{}],
      },
    ],
    showActionButtonGroup: false,
  });

const recordRef = ref({});
const [registerDrawer, {changeLoading, closeDrawer}] = useDrawerInner(
  async () => {
    await init();
  },
);
  async function init() {
    recordRef.value = {};
    await form1.resetFields();
    const initData = {};
    Object.assign(initData, recordRef.value);
    form1.setFieldsValue(initData);
  }
    /**
   * 核销
   * **/
  async function onSave(type) {
    await form1.validate();
    const formData = form1.getFieldsValue();
    const data = { ...recordRef.value, ...formData};
    const {  memberName, memberMobile, memberSource} = data;
      if (memberName && !memberMobile) {
        createMessage.error('手机号码和客户姓名必须同时填写或者同时留空');
        return false
      }
      if (memberMobile && !memberName) {
        createMessage.error('手机号码和客户姓名必须同时填写或者同时留空');
        return false
      }
    let memberCode = null;
    const nextFn = async () => {
      try {
        changeLoading(true);
        if (!!memberName && !!memberMobile) {
          (await POST('/membership/checkMemberMobile', {
            nickName: memberName,
            mobile: memberMobile
          }));
        }
        if (memberSource === '2') {
          const {resultMemberBaseInfoBean} = await PAGE('/assistant/douYinTicketCodeUse')(data)
          console.log(resultMemberBaseInfoBean)
          if (resultMemberBaseInfoBean){
            console.log(resultMemberBaseInfoBean,1234567890)
            state.memberCode = resultMemberBaseInfoBean.memberCode
          } else {
            console.log(12312312)
            state.memberCode = '-1'
          }
          createMessage.success('抖音凭证码核销成功!');
        } else if (memberSource === '6') {
          const {resultMemberBaseInfoBean} = await POST('/assistant/alipayCertificationUse', data) ?? {};
          if (!resultMemberBaseInfoBean) {
            return createMessage.error('券码不正确，请核对!');
          } else {
            if (resultMemberBaseInfoBean){
              state.memberCode = resultMemberBaseInfoBean.memberCode
            } else {
              state.memberCode = '-1'
            }
            createMessage.success('支付宝凭证码核销成功!');
          }
        } else if (memberSource === '7') {
          const {resultMemberBaseInfoBean} = await POST('/assistant/koubeiTicketCodeUse', data) ?? {};
          if (!resultMemberBaseInfoBean) {
            return createMessage.error('券码不正确，请核对!');
          } else {
            if (resultMemberBaseInfoBean){
              state.memberCode = resultMemberBaseInfoBean?.memberCode
            } else {
              state.memberCode = '-1'
            }
            createMessage.success('口碑凭证码核销成功!');
          }
        } else if (memberSource === '3') {
          const {resultMemberBaseInfoBean} = await POST('/assistant/mtVerificationReceiptPrepare', data) ?? {};
          if (!resultMemberBaseInfoBean) {
            return createMessage.error('券码不正确，请核对!');
          } else {
            console.log(resultMemberBaseInfoBean)
            if (resultMemberBaseInfoBean){
              state.memberCode = resultMemberBaseInfoBean?.memberCode
            } else {
              state.memberCode = '-1'
            }
            createMessage.success('美团凭证码核销成功!');
          }
        } else {
          return createMessage.error('暂不支持此平台券码!');
        }


        if (type === 2) {
          console.log(state.memberCode,type)
          await router.replace(`./index?memberCode=${state.memberCode}`);
        } else {
          closeDrawer();
        }
        emit('complete');
      } finally {
        changeLoading(false);
      }
    };
    await nextFn()
  }
</script>

<style lang="less" scoped>
  .card {
    margin: 8px 0 46px;
    padding: 12px;

    .form {
      padding: 24px 12px 0 0;
    }

    .data-group {
      display: flex;
      flex-flow: row wrap;
      align-items: center;
      cursor: pointer;
      gap: 8px 12px;

      .cell {
        position: relative;
        overflow: clip;

        width: 48px;
        height: 48px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        font-weight: 400;
        border-radius: 6px;
      }

      .tacit {
        border: 1px solid #e0e5ec;
        color: #fff;
      }

      .active {
        border: 1px solid @primary-color;
        color: #fff;
      }
    }
  }
</style>
